//创建axios实例
import axios from 'axios'
import qs from 'qs'
import { tokenStore } from '@/stores/models/tokenStore'
import { MessagePlugin } from 'tdesign-vue-next'

const userToken = tokenStore()
const instance = axios.create({
  baseURL: '/api', //接口统一域名
  timeout: 120 * 1000, //设置超时
  headers: {
    'Content-Type': 'application/json;charset=UTF-8'
  }
  // withCredentials:false
})

//请求拦截
instance.interceptors.request.use(
  (config = { autoQs: true }) => {
    if (!config.hasOwnProperty('autoQs')) {
      config.autoQs = true
    }
    //获取本地缓存中的token
    const token = userToken.getToken()
    token && (config.headers.Authorization = token)
    // 如果请求为post, 则将data参数转为json字符串
    if (config.method.toLocaleUpperCase() === 'POST' && config.autoQs) {
      config.data = qs.stringify(config.data)
      config.headers['Content-Type'] = 'application/x-www-form-urlencoded;charset=UTF-8'
    }
    return config
  },
  (error) => {
    //请求错误
    return Promise.reject(error)
  }
)

//响应拦截器
instance.interceptors.response.use(
  (response) => {
    if (response.data.code !== 200) {
      MessagePlugin.error(response.data.msg)
      return Promise.reject(response.data.msg)
    }
    return response.data.data
  },
  (error) => {
    const status = error.response?.status
    let message
    switch (status) {
      case 400:
        message = '请求错误'
        break
      case 401:
        message = '请求错误'
        break
      case 404:
        message = '请求地址错误'
        break
      case 408:
        message = '请求超时'
        break
      case 500:
        message = '服务器内部错误'
        break
      case 501:
        message = '服务未实现'
        break
      case 502:
        message = '网关错误'
        break
      case 503:
        message = '服务不可用'
        break
      case 504:
        message = '网关超时!'
        break
      case 505:
        message = 'http版本不支持'
        break
      default:
        message = error.response?.data
    }
    //请求报错处理
    MessagePlugin.error(message)
    return Promise.reject(error)
  }
)
export default instance
